package com.drojian.demo3.service.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.drojian.demo.R;

public class MusicService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        switch (action){
            case "play":
                playMusic();
                break;
            case "pause":
                pauseMusic();
                break;
            case "stop":
                stopMusic();
                break;
            case "root":
                root();
                break;

        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        exitMusic();
    }

    private MediaPlayer player;


    private void pauseMusic() {
        if(player!=null && player.isPlaying()){
            player.pause();
        }else {
            player.start();
        }
    }

    private void stopMusic() {
        if(player!=null){
            player.stop();
            player.reset();//重置
            player.release();//释放资源
            player = null;
            playMusic();
        }
    }
    private void exitMusic() {
        player.stop();
    }

    private void playMusic() {
        if(player==null){
            player = MediaPlayer.create(this,R.raw.music1);
        }
        player.start();
    }
    private void root() {
        if(player != null && player.isPlaying()){
            player.pause();
        }else {
            player.start();
        }
    }
}
